<template>
  <div class="container">
    <!-- tool start -->
    <el-form :model="formInline" label-width="120px" @keyup.enter.native="search">
      <el-row>
        <el-col :span="8">
          <el-form-item :label="$t('m.initInventory.inventory')">
            <el-input maxlength="13" show-word-limit v-model.trim="formInline.initialstocktakecode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.inventory.person')">
            <el-input maxlength="20" show-word-limit v-model.trim="formInline.stockuser"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.inventory.type')">
            <el-select v-model="formInline.stocktype">
              <el-option
                v-for="(item,index) in stocktypeOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.initInventory.state')">
            <el-select v-model="formInline.state">
              <el-option
                v-for="(item,index) in stateOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="SKU">
            <el-input maxlength="50" show-word-limit v-model.trim="formInline.productspeccode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.inventory.location')">
            <el-input maxlength="20" show-word-limit v-model.trim="formInline.locationcode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" align="right" @keyup.enter.native.stop>
          <el-button type="primary" @click="search" v-if="hasPermission('search')">{{$t('m.query')}}</el-button>
          <el-button @click="appoint" v-if="hasPermission('assign')">{{$t('m.shelves.appoint')}}</el-button>
          <el-button type="primary" @click="triggerInventory" v-if="hasPermission('add')">{{$t('m.initInventory.add')}}</el-button>
          <el-button @click="print" v-if="hasPermission('print')">{{$t('m.print')}}</el-button>
          <el-button @click="setComplete" v-if="hasPermission('setComplete')">{{$t('m.initInventory.setComplete')}}</el-button>
        </el-col>
      </el-row>
    </el-form>
    <!-- tool end -->

    <!-- table数据展示 start -->
    <el-table
      ref="table"
      stripe
      empty-text
      fit
      v-loading="tableLoading"
      class="table-wrap single-select-table"
      :data="tableData"
      :row-style="tableRowStyle"
      :row-class-name="tableRowClassName"
      @row-click="rowClick"
      @selection-change="handleSingleSelectionChange">
      <el-table-column align="center" type="selection" width="55"></el-table-column>
      <el-table-column align="center" type="index" :label="$t('m.index')" width="50"></el-table-column>
      <el-table-column align="center"  prop="initialstocktakecode" :label="$t('m.initInventory.stocktakecode')"></el-table-column>
      <!-- 处理时限 -->
      <el-table-column align="center" prop="status" :label="$t('m.initInventory.procLimit')">
        <template slot-scope="scope">
          <span v-if="scope.row.status === '超时'" class="tag overtime">{{$t('m.inventory.overtime')}}</span>
          <span v-if="scope.row.status === '警告'" class="tag warning">{{$t('m.inventory.warning')}}</span>
          <span v-if="scope.row.status === '正常'" class="tag normal">{{$t('m.inventory.normal')}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('m.state')">
        <template slot-scope="scope">{{scope.row.state|stateFilters}}</template>
      </el-table-column>
      <el-table-column align="center" :label="$t('m.inventory.type')">
        <template slot-scope="scope">{{scope.row.stocktype|stocktypeFilters}}</template>
      </el-table-column>
      <el-table-column align="center" :label="$t('m.inventory.method')">
        <template slot-scope="scope">{{scope.row.stockway|stockwayFilters}}</template>
      </el-table-column>
      <el-table-column align="center" prop="stockuser" :label="$t('m.inventory.person')"></el-table-column>
      <el-table-column align="center" :label="$t('m.inventory.date')">
        <template slot-scope="scope">{{scope.row.stocktime|dateFilter}}</template>
      </el-table-column>
      <el-table-column align="center" :label="$t('m.operation')">
        <template slot-scope="scope">
          <!-- 动碰盘点专用 -->
          <template v-if="hasPermission('table-check')&&scope.row.state===1">
            <el-button type="text" @click.stop="handleCheck(scope.row.initialstocktakeid )">{{$t('m.container.see')}}</el-button>
          </template>
          <!-- 动碰盘点专用 -->
          <template v-if="hasPermission('table-edit')&&!scope.row.state">
            <el-button type="text" @click.stop="handleEdit(scope.row.initialstocktakeid )">{{$t('m.edit')}}</el-button>
          </template>
          <template v-if="hasPermission('table-inventory')&&scope.row.state===2||scope.row.state===3">
            <el-button type="text" @click.stop="handleInventory(scope.row)">{{$t('m.inventory.do')}}</el-button>
          </template>
          <template v-if="hasPermission('table-delete')&&!scope.row.state">
            <el-button type="text" style="color:#f56c6c" @click.stop="handleDelete(scope.row.initialstocktakeid )">{{$t('m.delete')}}</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="sizes, prev, pager, next, jumper"
      :page-sizes="pageSizeList"
      :page-size="rowSize"
      :current-page="page"
      :total="totalRows"
      @current-change="currentChange"
      @size-change="handleSizeChange"
    ></el-pagination>
    <!-- table数据展示 end -->

    <!-- 指派负责人 start -->
    <assignPopup
      v-if="assignDialogVisible"
      :dialogVisible="assignDialogVisible"
      :options="taskleaderOptions"
      @close="assignDialogVisible=false"
      @save="appointmentSave"
    ></assignPopup>
    <!-- 指派负责人 end -->

    <!-- 根据盘点类型&&盘点方式，定制对应的盘点form start -->
    <inventoryStepPopup
      v-if="inventoryStepPopupVisible"
      :dialogVisible="inventoryStepPopupVisible"
      :options="[stocktypeOptions.slice(1),stockwayOptions]"
      @close="inventoryStepPopupVisible=false"
      @submit="submitInventoryInfo"
    ></inventoryStepPopup>
    <!-- 根据盘点类型&&盘点方式，定制对应的盘点form end -->

    <!-- 新增&编辑 盘点form start -->
    <initialInventoryPopup
      v-if="initialInventoryPopupVisible"
      :dialogVisible="initialInventoryPopupVisible"
      :extraInventoryType="extraInventoryType"
      @close="initialInventoryPopupVisible=false"
      @callback="getData"
    ></initialInventoryPopup>
    <!-- 新增&编辑 盘点form end -->

    <!-- 表格-盘点操作 start -->
    <handleInventoryPopup
      v-if="handleInventoryPopupVisible"
      :dialogVisible="handleInventoryPopupVisible"
      :detail="handleInventoryDetail"
      @close="handleInventoryClose"
      @callback="getData"
    ></handleInventoryPopup>
    <!-- 表格-盘点操作 end -->
    <!-- 打印 -->
    <printPopup
      v-if="popupVisible"
      :dialogVisible="popupVisible"
      :detail="printDetail"
      :printer="$store.state.basicInfo.userInfo.username"
      @close="popupVisible=false"
      @callback="getData"
    ></printPopup>
    <!-- 打印 -->

  </div>
</template>
<script>
import assignPopup from '@/components/common/assign'
import inventoryStepPopup from '@/components/initialInventory/inventory-step-popup'
import initialInventoryPopup from '@/components/initialInventory/initial-inventory-popup'
import printPopup from '@/components/initialInventory/printPopup'

let __this
export default {
  name:'initialInventory',
  data(){
    return {
      formInline:{
        initialstocktakecode:'', // 初盘单号
        state:'', // 盘点状态
        stocktype:'', // 盘点类型
        stockuser:'', // 盘点人
        locationcode:'', // 库位编码
        productspeccode:'', // sku
        stockway:'' //盘点方式（1盲盘 2 明盘）
      },
      inventoryTableList:[
        /*
          uniqueCode：表格根据什么字段进行合并
          tableRefs：表格的refs
        */
        { stocktype:1, uniqueCode:'productspeccode', tableRefs:'skuTable' }, // sku盘点
        { stocktype:2, uniqueCode:'locationcode', tableRefs:'locationTable' }, // 库位盘点
        { stocktype:3, uniqueCode:'collisioncode', tableRefs:'collisionTable' }, // 动碰盘点
        { stocktype:4, uniqueCode:'productspeccode', tableRefs:'warningTable' }, // 预警库存盘点
        { stocktype:5, uniqueCode:'locationcode', tableRefs:'ageTable' } // 库龄盘点
      ],

      extraInventoryType:{
        warning:[], // 预警库存盘点方式
        storageAge:[] // 库龄盘点方式
      },

      initialstocktakeid:0, // 盘点单id

      tableData:[],

      assignDialogVisible:false, // 控制指派负责人dialog显示隐藏
      taskleaderOptions:[],

      inventoryStepPopupVisible:false, // 盘点步骤dialog显示隐藏
      stepOptions:[],
      inventoryFormInfo:'', // 定制表格的盘点信息

      initialInventoryPopupVisible:false, // 新增&编辑盘点form dialog显示隐藏
      inventoryDetail:'', // 编辑or盘点时，记录后端返回的盘点detail

      handleInventoryPopupVisible:false, // 盘点操作 dialog显示隐藏
      handleInventoryDetail:{}, // 盘点单号&盘点表格数据
      printDetail:{},
      popupVisible:false,
      confirmDetailsInventoryPopupVisible:false // 二次确认&订单详情 dialog显示隐藏
    }
  },
  provide(){
    return {
      getFormInfo:() => this.inventoryFormInfo,
      getStockOptions:() => [this.stocktypeOptions, this.stockwayOptions],
      getInventoryDetail:() => this.inventoryDetail,
      getInventoryTableList:() => this.inventoryTableList
    }
  },
  beforeCreate(){
    __this = this
  },
  computed:{
    stateOptions(){
      return[
        // 盘点状态
        { label:this.$t('m.all'), value:'' },
        { label:this.$t('m.initInventory.state0'), value:0 },
        { label:this.$t('m.initInventory.state1'), value:1 },
        { label:this.$t('m.initInventory.state2'), value:2 },
        { label:this.$t('m.initInventory.state3'), value:3 }
      ]
    },
    stockwayOptions(){
      return[
        // 盘点方式
        { label:this.$t('m.inventory.method1'), value:1 },
        { label:this.$t('m.inventory.method2'), value:2, disabled:true }
      ]
    },
    stocktypeOptions(){
      return [
        ...[
          // 创建初盘单盘点类型
          { label:this.$t('m.all'), value:'' },
          { label:this.$t('m.initInventory.type1'), value:1 },
          { label:this.$t('m.initInventory.type2'), value:2 },
          { label:this.$t('m.initInventory.type3'), value:3 }
        ],
        ...[
          { label:`${this.$t('m.initInventory.type4')}`,
            remark:`${this.$t('m.inventory.remark1')}${this.extraInventoryType.warning.join('')}${this.$t('m.inventory.remark2')}`,
            value:4 },
          { label:`${this.$t('m.initInventory.type5')}`,
            remark:`${this.$t('m.inventory.remark3')}${this.extraInventoryType.storageAge.join('')}${this.$t('m.inventory.remark4')}`,
            value:5 }
        ]
      ]
    }
  },
  mounted(){
    this.getData()
    // 获取预警盘点&&库龄盘点的接口
    this.getStocktypeOptions()
  },
  components:{
    assignPopup,
    inventoryStepPopup,
    initialInventoryPopup,
    printPopup,
    handleInventoryPopup:() => import('@/components/initialInventory/handle-inventory-popup')
  },
  filters:{
    stateFilters(value){
      let result = __this.stateOptions.find(item => item.value === value)
      return result?result.label:''
    },
    stocktypeFilters(value){
      let result = __this.stocktypeOptions.find(item => item.value === value)
      return result?result.label:''
    },
    stockwayFilters(value){
      let result = __this.stockwayOptions.find(item => item.value === value)
      return result?result.label:''
    }
  },
  methods:{
    search(){
      this.page = 1
      this.getData()
    },
    getData(){
      let options = {
        method:'get',
        url:`/initialstocktake/page`,
        params:{...this.formInline, ...{
          page:this.page,
          rows:this.rowSize
        }}
      }
      this.tableLoading = true
      this.$axios(options).then(({ data }) => {
        this.tableData = data.records
        this.totalRows = data.total
        this.page = data.current
        setTimeout(()=>this.tableLoading=false,500)
        if (!this.tableData.length)
          return this.callbackMessage(this.$t('m.nodata'))
      })
    },
    // 获取盘点配置
    getStocktypeOptions(){
      let options = {
        method:'get',
        url:`/parametersettings/getparm4st`
      }
      this.$axios(options).then(({data})=>{
        let warning = [data.configuration4iw.value1,data.configuration4iw.value2]
        let storageAge = [data.configuration4la.value1]
        this.extraInventoryType = {warning,storageAge}
      })
    },
    // 指派--获取盘点人list
    appoint(){
      if (!this.tableRowSelected.length)
        return this.callbackMessage(this.$t('m.choose')+this.$t('m.inventory.inventory'))
      if (this.tableRowSelected[0].state !== 1)
        return this.callbackMessage(this.$t('m.inventory.cannot')
        )
      this.initialstocktakeid  = this.tableRowSelected[0].initialstocktakeid  // 获取当前选中的初盘单id，保存指派人的时候会用到
      let options = {
        method:'get',
        url:'/user/list'
      }
      this.$axios(options).then(({ data }) => {
        this.taskleaderOptions = data.map(item => {
          return { userid:item.id, username:item.username }
        })
        this.assignDialogVisible = true
      })
    },
    // 指派任务 保存按钮
    appointmentSave(stockuserid){
      let { username:stockuser } = this.taskleaderOptions.find(item => {
        return item.userid === stockuserid
      })
      let options = {
        method:'put',
        url:'/initialstocktake/assign',
        params:{
          initialstocktakeid:this.initialstocktakeid,
          stockuserid,
          stockuser
        }
      }
      this.$axios(options).then(({ message }) => {
        this.callbackMessage(message,'success')
        this.assignDialogVisible = false
        this.getData()
      })
    },

    // 设置完成btn -- 强制完成该盘点单
    setComplete(){
      if (!this.tableRowSelected.length)
        return this.callbackMessage(this.$t('m.choose')+this.$t('m.inventory.inventory'))
      let state =this.tableRowSelected[0].state
      if ([0,1].includes(state))
        return this.callbackMessage(this.$t('m.initInventory.setlimit'))
      this.initialstocktakeid = this.tableRowSelected[0].initialstocktakeid // 获取当前选中的初盘单id
      this.initialstocktakecode = this.tableRowSelected[0].initialstocktakecode //获取初盘单号
      // 存在未录入的checkqty，给予用户提示
      this.$confirm(this.$t('m.initInventory.tips1')+`${this.initialstocktakecode}`+this.$t('m.initInventory.tips2'), this.$t('m.initInventory.setComplete'), {
        confirmButtonText:this.$t('m.confirm'),
        cancelButtonText:this.$t('m.cancel'),
        type:'warning'
      }).then(() => {
        this.submitData(this.initialstocktakeid)
      }).catch(() => {
        // this.callbackMessage(this.$t('m.inventory.cancel'),'info')
      })
    },
    submitData(initialstocktakeid){
      let options = {
        method:'get',
        url:`/initialstocktake/mandatoryfinish`,
        params:{
          initialstocktakeid
        }
      }
      this.$axios(options).then(({ message }) => {
        this.callbackMessage(message,'success',1000,()=>{
          this.getData()
        })
      })
    },

    //  根据盘点单id获取盘点详情（新增，编辑，盘点）
    getStockTakeData(id, callback){
      let options = {
        method:'get',
        url:`/initialstocktake/${id}`
      }
      this.$axios(options).then(({ data }) => {
        callback && callback.call(this, data)
      })
    },
    // 触发盘点功能
    triggerInventory(){
      this.inventoryDetail = '' // 新增功能，盘点info置空
      this.inventoryStepPopupVisible = true
    },
    // 打印
    print(){
      if(this.tableRowSelected.length<1) return this.$message(this.$t('m.choose')+this.$t('m.inventory.inventory'))
      function printCallback(data){
        this.printDetail = data
        this.popupVisible = true
      }
      this.getStockTakeData(
        this.tableRowSelected[0].initialstocktakeid,
        printCallback
      )
    },

    // 根据盘点信息，定制表格
    submitInventoryInfo(form){
      this.inventoryFormInfo = form
      this.initialInventoryPopupVisible = true
    },
    // 表格-查看功能
    handleCheck(id){
      function checkCallback(data){
        this.inventoryDetail = data
        this.inventoryFormInfo = {
          stocktype:this.inventoryDetail.stocktype,
          stockway:this.inventoryDetail.stockway
        }
        this.initialInventoryPopupVisible = true
      }
      this.getStockTakeData(id, checkCallback)
    },
    // 表格-编辑功能
    handleEdit(id){
      function editCallback(data){
        this.inventoryDetail = data
        this.inventoryFormInfo = {
          stocktype:this.inventoryDetail.stocktype,
          stockway:this.inventoryDetail.stockway
        }
        this.initialInventoryPopupVisible = true
      }
      this.getStockTakeData(id, editCallback)
    },
    // 表格-盘点功能
    handleInventory(row){
      function inventoryCallback(data){
        this.inventoryDetail = data
        this.handleInventoryDetail.initialstocktakecode = row.initialstocktakecode
        this.handleInventoryPopupVisible = true
      }
      this.getStockTakeData(row.initialstocktakeid, inventoryCallback)
    },
    // 表格-删除功能
    handleDelete(id){
      this.$confirm(this.$t('m.deleteAlert'), this.$t('m.noticemessage'), {
        confirmButtonText:this.$t('m.confirm'),
        cancelButtonText:this.$t('m.cancel'),
        type:'warning'
      }).then(() => {
        let options = {
          method:'delete',
          url:`/initialstocktake/${id}`
        }
        this.$axios(options).then(() => {
          this.callbackMessage(this.$t('m.deleteSuccess'), 'success')
          this.getData()
        })
      }).catch(() => {
        this.callbackMessage(this.$t('m.printservice.cancel'), 'info')
      })
    },
    handleInventoryClose(){
      this.handleInventoryPopupVisible = false
      this.getData()
    }
  },
  beforeRouteLeave(to, form, next){
    this.assignDialogVisible=false
    this.inventoryStepPopupVisible=false
    this.handleInventoryPopupVisible=false
    this.popupVisible=false
    next()
  }
}
</script>
<style lang="scss" scoped>
.container ::v-deep .el-select {
  width: 100%;
}
.tag {
  display: inline-block;
  height: 20px;
  line-height: 20px;
  color: #fff;
  padding: 0 5px;
}
.overtime {
  background: #FF0000;
}
.warning {
  background: #FF9966;
}
.normal {
  background: #008000;
}
</style>